﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using WCFLib.Behaviour;

namespace WCFLib.Host
{
    /// <summary>
    /// 被拦截的服务主机
    /// </summary>
    public class InterceptedServiceHost : ServiceHost
    {
        public InterceptedServiceHost(Type type, Action initAction = null)
            : base(type)
        {
            if (initAction != null)
            {
                initAction();
            }
        }

        /// <summary>  
        /// 应用配置文件设置  
        /// </summary>  
        protected override void ApplyConfiguration()
        {
            base.ApplyConfiguration();

            InitIntercepter();
        }

        /// <summary>  
        /// 初始化拦截器  
        /// </summary>  
        private void InitIntercepter()
        {
            //加入参数检查服务  
            int endpointscount = this.Description.Endpoints.Count;
            var intercepter = new InterceptedOperationBehaviour();

            for (int i = 0; i < endpointscount; i++)
            {
                if (this.Description.Endpoints[i].Contract.Name != "IMetadataExchange")
                {
                    int Operationscount = this.Description.Endpoints[i].Contract.Operations.Count;

                    for (int j = 0; j < Operationscount; j++)
                    {
                        this.Description.Endpoints[i].Contract.Operations[j].Behaviors.Add(intercepter);
                    }
                }
            }
        }
    }
}
